package work.timejay.config;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @className:MybatisPlusConfig.java
 * @author:王文杰
 * @version:1.0.0
 * @description:mybatisPlus配置类
 * @createTime 2023年11月23日 14:22:00
 */
@Configuration
@Slf4j
@MapperScan(basePackages = {"work.timejay.user.mapper", "work.timejay.mapper"})
@EnableTransactionManagement
public class MybatisPlusConfig {

    /**
     * 插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor bean = new MybatisPlusInterceptor();
        //分页插件
        bean.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //乐观苏插件
        bean.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return bean;
    }

    /**
     * 自动填充功能
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                log.info("MybatisPlus Config Insert data---->{}", JSONUtil.toJsonStr(metaObject));
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
                this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
                this.strictInsertFill(metaObject, "version", Long.class, 0L);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                log.info("MybatisPlus Config Insert update---->{}", JSONUtil.toJsonStr(metaObject));
                //为空才会填充
                //this.strictUpdateFill()
                metaObject.setValue("updateTime", LocalDateTime.now(ZoneOffset.of("+8")));
            }
        };
    }
}
